package com.huawei.petSystemdemo.ui.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huawei.petSystemdemo.R;
import com.huawei.petSystemdemo.adapter.PetAdapter;

import com.huawei.petSystemdemo.bean.Banners;
import com.huawei.petSystemdemo.bean.Pets;
import com.huawei.petSystemdemo.databinding.FragmentHomeBinding;
import com.huawei.petSystemdemo.ui.Race.CatActivity;
import com.huawei.petSystemdemo.ui.search.SearchActivity;
import com.huawei.petSystemdemo.utils.ImgRepository;
import com.huawei.petSystemdemo.utils.MyRequest;
import com.huawei.petSystemdemo.utils.OnBindBottomListener;

import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;
    private SearchView searchView;
    private Banner mBanner;
    private int current = 1;
    private int size = 8;
    private LinearLayout cat;
    private LinearLayout dog;
    private LinearLayout small_pet;
    private String name;
    Map<String, Object> requestBody = new HashMap<>();

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        //搜索框
        searchView = root.findViewById(R.id.sv1);
        searchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SearchActivity.class);
                startActivity(intent);
            }
        });

        //轮播图
        mBanner = root.findViewById(R.id.catBanner);
        //图片资源
        ArrayList<Bitmap> imgeList = new ArrayList<>();
//        imgeList.add(R.drawable.one);//one
//        imgeList.add(R.drawable.two);//two
//        imgeList.add(R.drawable.three);//three
//        imgeList.add(R.drawable.four);//four
        requestBody.put("current", current);
        requestBody.put("size", size);
        requestBody.put("name", "home");
        MyRequest.get("/banner/getBanner_space", requestBody, json -> {

            JSONObject jsonObject = JSON.parseObject(json);
            List<Banners> list = jsonObject.getJSONArray("data").toJavaList(Banners.class);

            requestBody.clear();

            for(Banners banner : list) {

                ImgRepository.getImage("/banner/getBanner?img=" + banner.getImg(), bitmap -> {
                    imgeList.add(bitmap);
                    //设置轮播的动画效果,里面有很多种特效,可以到GitHub上查看文档。
                    mBanner.setImages(imgeList);//设置图片资源
                    mBanner.setImageLoader(new ImageLoadBanner());
                    // mBanner.setBannerTitles(titleList); //（当banner样式有显示title时）
                    mBanner.setDelayTime(1000);//设置轮播时间3秒切换下一图设置标题集合
                    mBanner.isAutoPlay(true);
                    mBanner.setIndicatorGravity(BannerConfig.CENTER);
                    mBanner.setBannerAnimation(Transformer.Accordion);
                    mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置banner显示样式（带标题的样式）
                    mBanner.start();//开始进行banner渲染
                });
            }

        });

//
//        //轮播标题
//        String[] mtitle = {"图片1", "图片2", "图片3", "图片4"};
//        List<String> titleList = new ArrayList<>();
//        for (int i = 0; i < mtitle.length; i++) {
//            //imgeList.add(imgeList[i]);//把图片资源循环放入list里面
//            titleList.add(mtitle[i]);//把标题循环设置进列表里面
//        }




        //主页商品列表
        RecyclerView list = root.findViewById(R.id.recycle);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        list.setLayoutManager(manager);

        List<Pets> petsList = new ArrayList<>();

        requestBody.put("current", current + "");
        requestBody.put("size", size + "");

       // MyRequest.baseUrl = Request.url;
        MyRequest.get("/pet/getAll", requestBody, json -> {

            System.out.println(json);
            JSONObject obj = JSON.parseObject(json);
            int statusCode = obj.getInteger("statusCode");
            String errMessage = obj.getString("errMessage");
            List<Pets> data = obj.getJSONArray("data").toJavaList(Pets.class);

            System.out.println(statusCode);
            System.out.println(errMessage);
            System.out.println(data);

            petsList.addAll(data);

            PetAdapter petAdapter = new PetAdapter(petsList, getContext());
            petAdapter.setListener(new OnBindBottomListener<List<Pets>>() {

                @Override
                public void bind(List<Pets> list1) {
                    current++;
                    requestBody.put("current", current + "");
                    requestBody.put("size", size + "");
                    MyRequest.get("/pet/getAll", requestBody, json -> {
//                        String json = response.body().string();
                        System.out.println(json);
                        JSONObject obj = JSON.parseObject(json);
                        int statusCode = obj.getInteger("statusCode");
                        String errMessage = obj.getString("errMessage");
                        List<Pets> data = obj.getJSONArray("data").toJavaList(Pets.class);
                        System.out.println(statusCode);
                        System.out.println(errMessage);
                        System.out.println(data);
                        // System.out.println(data.get(0).getName());


                        if (data.size() != 0)
                        {
                            System.out.println("新数据");
                            petsList.addAll(data);
                            petAdapter.notifyDataSetChanged();
//                      list.setAdapter(petAdapter);
                        }
                    });
                }
            });
            list.setAdapter(petAdapter);

        });



        //猫猫馆
        cat = root.findViewById(R.id.cat);
        cat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), CatActivity.class);
                intent.putExtra("race","猫");
                startActivity(intent);
            }
        });

        //狗狗馆
        dog = root.findViewById(R.id.dog);
        dog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), CatActivity.class);
                intent.putExtra("race", "狗");
                startActivity(intent);
            }
        });

        //小宠馆
        small_pet = root.findViewById(R.id.small_pet);
        small_pet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), CatActivity.class);
                intent.putExtra("race", "小宠物");
                startActivity(intent);
            }
        });

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    class ImageLoadBanner extends ImageLoader {

        @Override
        public void displayImage(Context context, Object bitmap, ImageView imageView) {
            imageView.setImageBitmap((Bitmap) bitmap);
        }
    }
}